/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    const queue = [];
    const swapChildren = (node) => {
        const temp = node.left;
        node.left = node.right;
        node.right = temp;
    }
    if (root != null) {
        queue.push(root);
    }
    while(queue.length > 0) {
        const node = queue[0];
        swapChildren(node);
        if(node.left != null)
            queue.push(node.left);
        if(node.right != null)
            queue.push(node.right);
        queue.shift();  // 弹出首元素
    }
    return root;
};